<?php namespace lfy;

//!	LFY's error handler. 

class error{

	//!	PHP's E_ constants indexed by their integer value

	public static $constants = array(
		E_ERROR => 'E_ERROR',
		E_WARNING => 'E_WARNING',
		E_PARSE => 'E_PARSE',
		E_NOTICE => 'E_NOTICE',
		E_CORE_ERROR => 'E_CORE_ERROR',
		E_CORE_WARNING => 'E_CORE_WARNING',
		E_COMPILE_ERROR => 'E_COMPILE_ERROR',
		E_COMPILE_WARNING => 'E_COMPILE_WARNING',
		E_USER_ERROR => 'E_USER_ERROR',
		E_USER_WARNING => 'E_USER_WARNING',
		E_USER_NOTICE => 'E_USER_NOTICE',
		E_STRICT => 'E_STRICT',
		E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
		E_DEPRECATED => 'E_DEPRECATED',
		E_USER_DEPRECATED => 'E_USER_DEPRECATED',
		E_ALL => 'E_ALL'				 
	);

	//!	user func for PHP's set_error_handler

	public static function handle($E, $message, $file, $line){
	
		$PHP = false;
		
		$FATAL = $E & (E_ERROR | E_USER_ERROR);
		
		if($FATAL){
			
			$Type = 'Fatal Error';	
			$PHP = ($E == 1);
			
		}else if(isset(self::$constants[$E])){
			
			// get error name for output
			$Type = substr(self::$constants[$E], 2);
			
			if(!$PHP = (substr($Type, 0, 5) != 'USER_')) 
				$Type = substr($T, 5);
		
		}else $Type = "Error ($n)";
		
		$PROJECT = $PHP ? 'PHP' : ( defined('LFY_PROJECT_UPPER') ? LFY_PROJECT_UPPER : 'LFY' );
		
		$error_string = "$PROJECT $Type: $message in $file on line $line";
		
		if(LFY_CLI_MODE){
		
			if($E & error_reporting())  
				fwrite(STDERR, "$error_string\n");
		
		}else{
		
			if($E & error_logging()) 
				error_log($error_string);		

			if(($E & error_reporting()) && ini_get('display_errors')){

				if(!$FATAL && !headers_sent() && !ob_get_level()){
					ob_start();
					echo "<br />\n<i>Output buffering has been started to avoid killing headers with the following error;</i>";
				}
				
				echo "<br />\n<b>$PROJECT $Type:</b> $message in <b>$file</b> on line <b>$line</b><br />\n";
				
			}
		
		}

		if($FATAL) 
			exit(E_ERROR);
		
		return true;
	}

}

